package com.spring5.learning;

import java.lang.reflect.Method;

import com.spring5.learning.bean.Person;
import org.junit.Test;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.util.ReflectionUtils;

/**
 * @author xin
 * @version 1.0
 */
public class Main {

    @Test
    public void processor() {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
        Person person = ctx.getBean(Person.class);
        person.walkDog();
    }

    @Test
    public void doWith() {
        ReflectionUtils.doWithLocalFields(Person.class, field -> System.out.println(field.getName()));
        ReflectionUtils.doWithLocalMethods(Person.class, method -> System.out.println(method.getName()));
    }


    @Test
    public void proxy() {
        ProxyFactory factory = new ProxyFactory(new House());
        //factory.setProxyTargetClass(true);
        factory.addAdvice(new BeforeConstructAdvice());

        House house = (House) factory.getProxy();
        house.construct();
    }



    class House {
        void construct() {
            System.out.println("construct a house");
        }
    }

    class BeforeConstructAdvice implements MethodBeforeAdvice {

        @Override
        public void before(Method method, Object[] args, Object target) throws Throwable {
            if (method.getName().equals("construct")) {
                System.out.println("give permission to construct a house");
            }
        }
    }
}
